$package('wstuo.customFilter');
$import('wstuo.customFilter.filterCM');
/**  
 * @author wstuo 
 * @constructor CustomFilterDTO
 * @description 过滤器主函数.
 * @since version 1.0 
 */
wstuo.customFilter.filterGrid_Operation = function(){
	this.actionNo=0;
	this.tagID="";
	this.i=0;
	this.filterCategory="";
	this.entityClass="";
	this.ciReport='';
	return {
		/**
		 * @description 动态加载条件,默认第一个为编号
		 * @param options 值对应的key
		 */
		addExpress_TermSet:function(options){
			$('#express_propName').html(wstuo.customFilter.filterCM.loadConditionHTML(options));
			setTimeout(function(){
				$('#express_propName').unbind().change(function(){
					wstuo.customFilter.filterGrid_Operation.setExpPVHTML();
					wstuo.customFilter.filterGrid_Operation.setExpOperation();
				});
				$('#filterGrid_addExpressToList').unbind().click(wstuo.customFilter.filterGrid_Operation.addExpressToList);
			},1000);
			$('#express_operator').html(wstuo.customFilter.filterCM.loadOperatorByString());
		},
		
		/**
		 * @description 获取选择的字段.
		 */
		addAndEdit_matchPname:function(){
			return $("#express_propName").find("option:selected").text();
		},
		/**
		 * @description 获取选择的字段国际化.
		 */
		getPropDisplayName:function(){
			return $("#express_propName").find("option:selected").attr('id');
		},
		/**
		 * @description 获取选择的查询方式.
		 */
		addAndEdit_matchOperator:function(){
			return $("#express_operator").find("option:selected").text();
		},
		/**
		 * @description 获取选择的查询方式的国际化.
		 */
		getDisplayOperator:function(){
			return $("#express_operator").find("option:selected").attr('id');
		},
		/**
		 * @description 获取值内容.
		 */
		addAndEdit_matchPvalue:function(){		
			return wstuo.customFilter.filterCM.getPvalue('#express_propName','#express_propertyValue','#express_propertyName');
		},
		/**
		 * @description 设置值显示方式.
		 */
		setExpPVHTML:function(){
			var flag=$('#express_propName').val();
			wstuo.customFilter.filterCM.createPVEvent(flag,'#express_propValueDIV','express_propertyName','express_propertyValue','');
		},
		/**
		 * @description 设置符号.
		 */
		setExpOperation:function(){
			wstuo.customFilter.filterCM.setExpOperation('#express_propName','#express_operator');
		},
		/**
		 * 清空数据
		 */
		clearData:function(){
			//清空数据
			$('#filter_name').val("");
			$('#filter_desc').val("");
			//清空规则列表
			$('#customFilter_constraintsTable tbody').html('');
		},
		/**
		 * @description 打开过滤器页面.
		 * @param options 值对应键
		 * @param filterCategoryF 过滤器分类
		 * @param entityClassF 实体class
		 * @param pageId 页面元素
		 */
		openCustomFilterWinR:function(options,filterCategoryF,entityClassF,pageId){
			ciReport='report';
			wstuo.customFilter.filterGrid_Operation.openCustomFilterWin(options,filterCategoryF,entityClassF,pageId);
		},
		/**
		 * @description 打开过滤器页面.
		 * @param options 值对应键
		 * @param filterCategoryF 过滤器分类
		 * @param entityClassF 实体class
		 * @param pageId 页面元素
		 */
		openCustomFilterWin:function(options,filterCategoryF,entityClassF,pageId){
			tagID="#"+pageId;
			filterCategory=filterCategoryF;
			entityClass=entityClassF;
			wstuo.customFilter.filterGrid_Operation.clearData();
			$('#customFilter_search').hide();
			$('#customFilter_delete').hide();
			$('#filter_Id').val("");
			$("#loadShareGroupGrid_sign").val("");//标记共享组 will

			windows('customFilterWindow',{width:700});
			$('#customFilterDTO_share').eq(0).attr('selected', 'true');
			//加载字段操作条件
			wstuo.customFilter.filterGrid_Operation.addExpress_TermSet(options);
			wstuo.customFilter.filterGrid_Operation.setExpPVHTML();
			wstuo.customFilter.filterGrid_Operation.setExpOperation();
			wstuo.customFilter.filterGrid_Operation.loadFilter();
			$('#customFilter_save').unbind().click(wstuo.customFilter.filterGrid_Operation.saveFilter);
			$('#customFilter_delete').unbind().click(wstuo.customFilter.filterGrid_Operation.deleteFilter);
			$("#customFilterWindow").dialog({
				close: function(event, ui) {
					setTimeout(function(){
						ciReport='';
						$("#customFilterWindow").dialog('destroy');//销毁
					},0);
				} 
			});
		},
		/**
		 * @description 加载各模块的用户过滤器
		 * @param valueID 值元素
		 * @param filterCategory 过滤器分类
		 */
		loadFilterByModule:function(valueId,filterCategory){
				$(valueId).empty(); 				
				tagID=valueId;
				$(valueId).append('<option value="-1">-- '+i18n['lable_filter']+' --</option>');
				var url = 'filter!findCustomFilter.action?queryDTO.filterCategory='+filterCategory+'&&queryDTO.userName='+userName;
				$.post(url,function(filters){		
					if(filters!=null && filters.length>0){
						for(var i=0;i<filters.length;i++){	
							$(valueId).append('<option value="'+filters[i].filterId+'">'+filters[i].filterName+'</option>');
						}
					}
				});

		},
		/**
		 * @description 加载用户过滤器
		 */
		loadFilter:function(){
			setTimeout(function(){//延迟加载
						
						$('#filterByUser').empty(); 
				
						$('#filterByUser').html('<option value="0">-- '+i18n['pleaseSelect']+' --</option>');
						var url = 'filter!findMyFilters.action?queryDTO.filterCategory='+filterCategory+'&&queryDTO.userName='+userName;
						$.post(url,function(filters){
							if(filters!=null && filters.length>0){
								for(var i=0;i<filters.length;i++){
									$('<option value="'+filters[i].filterId+'">'+filters[i].filterName+'</option>').appendTo('#filterByUser');
								}
							}
						});
							
					},0);
		},
		/**
		 * 根据过滤器编号，查询过滤器信息，并填充到页面.
		 * @param filterId 过滤器Id
		 */
		getFilterSearchByUser:function(filterId){
			$('#filter_Id').val(filterId);
			wstuo.customFilter.filterGrid_Operation.clearData();
			$("#loadShareGroupGrid_sign").val("");
			if(filterId=="0"){
				$('#customFilter_search').hide();
				$('#customFilter_delete').hide();
				$(".express_attr").remove();
				endProcess();
			}else{
				var url='filter!findFilterById.action?queryDTO.filterId='+filterId;
				$.post(url,function(customFilterDTO){
					endProcess();
					$('#customFilterDTO_share').val(customFilterDTO.share);
					if(customFilterDTO.share=="sharegroup"){
						$('#selectShareGroup').show();
					}else{
						$('#selectShareGroup').hide();
					}
					$('#customFilterDTO_share_groups').val(customFilterDTO.shareGroupIds);
					$('#filter_name').val(customFilterDTO.filterName);
					if(customFilterDTO.filterDesc!=null && customFilterDTO.filterDesc!=""){
						$('#filter_desc').val(customFilterDTO.filterDesc);
					}else{
						$('#filter_desc').val("");
					}					
					var expressions=customFilterDTO.expressions;
					wstuo.customFilter.filterGrid_Operation.fillExpressData(expressions);
					$('#customFilter_search').show();
					$('#customFilter_delete').show();
				});
			}
			
		},
		/**
    	 * 保存更新过滤器.
    	 */
		saveFilter:function(){
			//if($('#customFilterWindow form').form('validate')){
				var filterId=$('#filter_Id').val();
				var save_filter_name=$('#filter_name').val();
				if(save_filter_name == ''){
					msgAlert(i18n['msg_filter_name'],'info');
				}else{
				
				$("#loadShareGroupGrid_sign").val("");
				var ids = $("#filtershareGroupGrid").getDataIDs();
				$('#customFilterDTO_share_groups').val(ids);
				if(filterId=="0"||filterId==""){
					var _url='filter!save.action';
					var filter=wstuo.customFilter.filterCM.getFilterInfo('#customFilterWindow','#customFilter_constraintsTable',userName,filterCategory,entityClass);//取得表达式数组
					//显示进程
					startProcess();
					 $.post(_url,filter, function(){
							//隐藏进程
							endProcess();
						 	msgShow(i18n['saveSuccess'],'show');
						 	wstuo.customFilter.filterGrid_Operation.loadFilter();
						 	wstuo.customFilter.filterGrid_Operation.loadFilterByModule(tagID,filterCategory);//重新加载下拉框
						 	if(filterCategory=="ci" && ciReport==''){
								$('#itsmMainTab').tabs('getSelected').panel('refresh');
							}
						 	ciReport='';
						 	$('#customFilterWindow').dialog('close');
					});
				}else{
					var _url='filter!update.action';
					var filter=wstuo.customFilter.filterCM.getFilterInfo('#customFilterWindow','#customFilter_constraintsTable',"","","");//取得表达式数组
					$.extend(filter,{'customFilterDTO.filterId':filterId});
					 $.post(_url,filter, function(){
						 	msgShow(i18n['editSuccess'],'show');
						 	wstuo.customFilter.filterGrid_Operation.loadFilter();
						 	wstuo.customFilter.filterGrid_Operation.loadFilterByModule(tagID,filterCategory);//重新加载下拉框
						 	if(filterCategory=="ci" && ciReport==''){
								$('#itsmMainTab').tabs('getSelected').panel('refresh');
							}
						 	ciReport='';
						 	$('#customFilterWindow').dialog('close');
					});
				}
			}
		},
		/**
    	 * 删除过滤器
    	 */
		deleteFilter:function(){
			msgConfirm(i18n['msg_msg'],'<br/>'+i18n['msg_confirmDelete'],function(){
    				var id=$('#filter_Id').val();
    				var ids=new Array(id);
    				var _url='filter!delete.action?ids='+ids;
    				//显示进程
    				startProcess();
    				$.post(_url,function(){
    					//隐藏进程
    					endProcess();
    					msgShow(i18n['deleteSuccess'],'show');
    					wstuo.customFilter.filterGrid_Operation.loadFilter();
    				 	wstuo.customFilter.filterGrid_Operation.loadFilterByModule(tagID,filterCategory);//重新加载下拉框
						//$('#itsmMainTab').tabs('getSelected').panel('refresh');
    				 	//$('#customFilterWindow').dialog('close');
    				 	wstuo.customFilter.filterGrid_Operation.reloadGridByfilterCategory(filterCategory);
    				});
    		});
		},
		reloadGridByfilterCategory:function(filterCategory){
			var _param={};
			if(filterCategory=="request"){
				var _url='request!findRequests.action?requestQueryDTO.lastUpdater='+userName;	
				$.extend(_param,{'requestQueryDTO.filterId':0});
				$('#requestGrid').jqGrid('setGridParam',{page:1,url:_url,postData:_param}).trigger('reloadGrid');
			}else if(filterCategory=="problem"){
				var _url = 'problem!findProblemPager.action';	
				$('#problemGrid').jqGrid('setGridParam',{page:1,url:_url,postData:_param}).trigger('reloadGrid');
			}else if(filterCategory=="change"){
				var _url = 'change!findPagerChange.action';		
				$('#changeGrid').jqGrid('setGridParam',{page:1,url:_url,postData:_param}).trigger('reloadGrid');
			}else if(filterCategory=="ci"){
				var _url='ci!cItemsFind.action?ciQueryDTO.loginName='+userName;	
				$.extend(_param,{'ciQueryDTO.filterId':0});
				$('#configureGrid').jqGrid('setGridParam',{page:1,url:_url,postData:_param}).trigger('reloadGrid');
			}else if(filterCategory=="knowledge"){
				var _url='knowledgeInfo!findAllKnowledges.action';
				$('#knowledgeGrid').jqGrid('setGridParam',{page:1,url:_url,postData:_param}).trigger('reloadGrid');
			}
			wstuo.customFilter.filterGrid_Operation.clearData();
			$('#customFilter_search').hide();
			$('#customFilter_delete').hide();
			$('#filter_Id').val("");
			$("#loadShareGroupGrid_sign").val("");
		},
		/**
		 * @description 添加表达式.
		 */
		addExpressToList:function(){
			var propName = $('#express_propName').val();
			var operator=$('#express_operator').val();
			var joinType = $("input[type=radio][name=express_joinType][checked]").val();
			var propertyValue = $('#express_propertyValue').val();
			var propType=wstuo.customFilter.filterCM.switchExpressPropType('#express_propName');
			//判断是否已存在此条件
			var thisFilterValueHave=false;
			var i=0;
			if(propName.indexOf("financeCorrespond")>-1){
				if($('#fimappingYes').attr('checked')){
					propertyValue="true";
				}else{
					propertyValue="false";
				}
			}
			$("#customFilter_constraintsTable input[name=express_propertyValue]").each(function(){
				if(propName=='serviceDirectoryItem.subServiceIds_subServiceId'){
					propName='serviceDirectory.eventId';
				}
				if(this.value===propertyValue && propName.indexOf($("#customFilter_constraintsTable input[name=express_propName]").eq(i).val())!=-1){
					thisFilterValueHave=true;
					
				}
				var inputValue=$("#express_propValueDIV input[id=express_propertyValue]").val();
				var inputPropName=$("#express_propValueDIV input[id=express_propName]").eq(i).val();
				var tableInptuValue=$("#customFilter_constraintsTable input[name=express_propertyValue]").eq(i).val();
				var tableHiddenValue=$("#customFilter_constraintsTable input[name=express_propertyDisplayValue]").eq(i).val();
				//如果值和属性名
				if(inputValue == tableInptuValue && inputPropName == propName){
					thisFilterValueHave=true;
				}
				i++;
				
			});
			i=0;
			$("#customFilter_constraintsTable input[name=express_propName]").each(function(){
				if(this.value==="serviceLists.eventId" && propName=="serviceDirectoryItem.subServiceId_subServiceId"){
					thisFilterValueHave=true;
				}
				var inputValue=$("#express_propValueDIV input[id=express_propertyValue]").val();
				var inputPropName=$("#express_propValueDIV input[id=express_propName]").eq(i).val();
				
				var tableInptuValue=$("#customFilter_constraintsTable input[name=express_propertyValue]").eq(i).val();
				var tableHiddenValue=$("#customFilter_constraintsTable input[name=express_propertyDisplayValue]").eq(i).val();
				//如果值和属性名
				if(inputValue == tableInptuValue && inputPropName == propName){
					thisFilterValueHave=true;
				}
				i++;
			});
			if(thisFilterValueHave){
				msgAlert(i18n['label_requireHave'],'info');
			}else{
				if(propName.indexOf("department")==-1 && propName.indexOf(".loginName")==-1 && propType=="String" && propName.indexOf("knowledgeStatus")==-1){
					propertyValue="%"+propertyValue+"%";
				}
				if("creator_loginName"==propName||"userName_loginName"==propName||"owner_loginName"==propName||"originalUser_loginName"==propName){
					propertyValue=propertyValue.replace(/%/g,'');
				}
				if(propName!='createdBy.loginName' &&  propName!='createdBy.orgnization.orgNo'){
					propName=propName.substring(0,propName.lastIndexOf('_'));
				}
				if(propName.indexOf("financeCorrespond")>-1){
					if($('#fimappingYes').attr('checked')){
						propertyValue="true";
						$('#express_propertyValue').val(i18n['label_basicConfig_deafultCurrencyYes']);
					}else{
						propertyValue="false";
						$('#express_propertyValue').val(i18n['label_basicConfig_deafultCurrencyNo']);
					}
				}
				if(propertyValue!=""&&propertyValue!="%%"){
					i++;
					if("serviceDirectoryItem.subServiceId"==propName){
						propName="serviceLists.eventId";
					}
					if("serviceDirectoryItem.subServiceIds"==propName){
						propName="serviceDirectory.eventId";
					}
						
					var trHTML=wstuo.customFilter.filterCM.replaceExpressStr(i,
							wstuo.customFilter.filterGrid_Operation.addAndEdit_matchPname(),
							propType,
							wstuo.customFilter.filterGrid_Operation.getPropDisplayName(),
							propName,
							wstuo.customFilter.filterGrid_Operation.addAndEdit_matchOperator,
							wstuo.customFilter.filterGrid_Operation.getDisplayOperator,
							operator,
							wstuo.customFilter.filterGrid_Operation.switchOrAnd(joinType),
							wstuo.customFilter.filterGrid_Operation.switchOrAnd(joinType),
							wstuo.customFilter.filterGrid_Operation.addAndEdit_matchPvalue(),
							wstuo.customFilter.filterGrid_Operation.addAndEdit_matchPvalue(),
							propertyValue,
							"#constraint"+i
					);
					$("#customFilter_constraintsTable tbody").append(trHTML);
					//请求分类递归子分类
					var column_flag=$('#express_propName').val();
					if("requestCategory.eventId_ReventId"==column_flag||  "category.eventId_PeventId"==column_flag || "category.eventId_CeventId"==column_flag || "category.eventId_KeventId"==column_flag){
						$.post('event!findSubCategorysByResType.action?categoryId='+$('#express_propertyValue').val()+'&types=Request',function(res){
								if(res!=null && res.length>0){
									var i = 1;
									$.each(res,function(k,v){
										i++;
										var subCategory = wstuo.customFilter.filterCM.replaceExpressStr(i,
												wstuo.customFilter.filterGrid_Operation.addAndEdit_matchPname(),
												propType,
												wstuo.customFilter.filterGrid_Operation.getPropDisplayName(),
												propName,
												wstuo.customFilter.filterGrid_Operation.addAndEdit_matchOperator,
												wstuo.customFilter.filterGrid_Operation.getDisplayOperator,
												operator,
												wstuo.customFilter.filterGrid_Operation.switchOrAnd('or'),
												wstuo.customFilter.filterGrid_Operation.switchOrAnd('or'),
												v.eventName,
												v.eventName,
												v.eventId,
												"#constraint"+i
										);
										//判断是否已存在此条件
										var thisFilterValueHave=false;
										var count=0;
										$("#customFilter_constraintsTable input[name=express_propertyValue]").each(function(){
											 if(this.value==v.eventId && propName.indexOf($("#customFilter_constraintsTable input[name=express_propName]").eq(count).val())!=-1){
												 thisFilterValueHave=true;
											 }
											 count++;
										});
										if(!thisFilterValueHave){
											$("#customFilter_constraintsTable tbody").append(subCategory);
										}
									});
								}
							});	
					}
					//加入配置项分类子分类
					/*if("category.cno_CIeventId"==column_flag){
						$.post('ciCategory!findSubCategorysByResType.action?cno='+$('#express_propertyValue').val(),function(res){
							
							if(res!=null && res.length>0){
								var i = 1;
								$.each(res,function(k,v){
									i++;
									var subCategory=common.config.customFilter.filterCM.replaceExpressStr(i,
											common.config.customFilter.filterGrid_Operation.addAndEdit_matchPname(),
											propType,
											common.config.customFilter.filterGrid_Operation.getPropDisplayName(),
											propName,
											common.config.customFilter.filterGrid_Operation.addAndEdit_matchOperator,
											common.config.customFilter.filterGrid_Operation.getDisplayOperator,
											operator,
											common.config.customFilter.filterGrid_Operation.switchOrAnd('or'),
											common.config.customFilter.filterGrid_Operation.switchOrAnd('or'),
											v.cname,
											v.cname,
											v.cno,
											"#constraint"+i
									);
									//判断是否已存在此条件
									var thisFilterValueHave=false;
									var count=0;
									$("#customFilter_constraintsTable input[name=express_propertyValue]").each(function(){
										 if(this.value==v.cno && propName.indexOf($("#customFilter_constraintsTable input[name=express_propName]").eq(count).val())!=-1){
											 thisFilterValueHave=true;
										 }
										 count++;
									});
									if(!thisFilterValueHave){
										$("#customFilter_constraintsTable tbody").append(subCategory);
									}
								});
							}
						});	
				 }*/
				//清空数据
				$('#express_propertyValue,#express_propertyName').val('');
				wstuo.customFilter.filterCM.judgeAttr();
				}else{
					if(propName=="knownError" && propertyValue==""){
						msgAlert(i18n['label_requireHave'],'info');
					}else{
						msgAlert(i18n['msg_filter_conditionCanNotBeNull'],'info');
					}
				}
			}
		},
		/**
		 * 取得链接方式Html
		 * @param joinType 链接类型
		 */
		switchOrAnd:function(joinType){
			var andOr="<option value='or'>or</option><option value='and'>and</option>";
			if(joinType=='and'){
				andOr="<option value='and'>and</option><option value='or'>or</option>";
			}
			return andOr;
		},
		/**
		 * @description 查找表达式并显示.
		 * @param data 过滤器集合
		 */
		fillExpressData:function(data){
			 for(var i=0;i<data.length;i++){
				 if(data[i]!=null){
					 var propDisplayName=i18n[data[i].propDisplayName];
					 if(!propDisplayName)propDisplayName=data[i].propDisplayName;
						var trHTML=wstuo.customFilter.filterCM.replaceExpressStr(i,
								propDisplayName,
								data[i].propType,
								data[i].propDisplayName,
								data[i].propName,
								i18n[data[i].displayOperator],
								data[i].displayOperator,
								data[i].operator,
								wstuo.customFilter.filterGrid_Operation.switchOrAnd(data[i].joinType),
								wstuo.customFilter.filterGrid_Operation.switchOrAnd(data[i].joinType),
								data[i].propDisplayValue,
								data[i].propDisplayValue,
								data[i].propValue,
								"#constraint"+i
						);
					$("#customFilter_constraintsTable tbody").append(trHTML);
				 }
			 }
			 wstuo.customFilter.filterCM.judgeAttr();
		}
	};
}();